package io.renren.modules.mqtt.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson.JSON;
import com.mchange.v2.lang.ThreadUtils;
import io.renren.modules.device.service.TDeviceService;
import io.renren.modules.mqtt.MqttPushClient;
import io.renren.modules.mqtt.entity.MqttEvent;
import io.renren.modules.mqtt.entity.MqttLog;
import io.renren.modules.mqtt.service.IEventService;
import io.renren.modules.mqtt.service.IMqttLogService;
import io.renren.modules.mqtt.service.MqttService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * //Add the class description
 *
 * @author lhb
 * @date 2023/6/12
 */
@Service("loginEventService")
@Slf4j
public class LoginEventService implements IEventService {
    @Autowired
    private TDeviceService deviceService;
    @Autowired
    private MqttPushClient client;
    @Autowired
    private ReplyEventService replyEventService;

    @Autowired
    private IMqttLogService mqttLogService;

    @Override
    public boolean eventHandler(MqttEvent event) {
        // 判断accessId是否为设备，存在数据库中
        String deviceId = event.getAccessId();
        if (StringUtils.isEmpty(deviceId)) {
            // 设备不存在则 查找paraList参数 ,"paraList":[{"paraName":"terminalNo","value":860326065878835}
            deviceId = event.getParaList().get(0).get("value");
        }
        boolean res = deviceService.updateOnlineStatus(deviceId, true);
        // 应答结果0：成功；1：失败
        new Thread(new Runnable() {
            @Override
            public void run() {
                log.debug("启动线程，回复消息");
                replyMsg(event, res ? 0 : 1);
            }
        }).start();

        return res;
    }

    @Override
    public String getMessType() {
        return "login";
    }

    private void replyMsg(MqttEvent event, int result) {
        String newTopic = "zhny-reply";
        MqttEvent replyEvent = new MqttEvent();
        replyEvent.setReplyMsgType(event.getMsgType());
        replyEvent.setMsgType(newTopic);
        replyEvent.setAccessId(event.getAccessId());
        replyEvent.setParaList(event.getParaList());
        replyEvent.setSerialNo(event.getSerialNo());
        replyEvent.setResult(result);
        MqttLog mqttLog = new MqttLog();
        mqttLog.setTopic(newTopic);
        mqttLog.setMessage(JSON.toJSONString(replyEvent));
        mqttLog.setCreateTime(new Date());
        mqttLog.setMsgFlag(1);//发消息
        mqttLogService.save(mqttLog);

        client.pushlish(newTopic, JSON.toJSONString(replyEvent));
//        client.refresh();
//        try {
//            Thread.sleep(3000);
//            log.debug("发布消息后，重新连接mqtt");
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
    }
}
